# encoding=utf-8
import os
import backup
import config
import database
import fileio
import re
from chkinvpic import ChkInvPic
import backupdb
import delartpic

# 产品名称
PRODUCTION_NAME    = 'SePiCer'
# 产品版本
PRODUCTION_VERSION = '1.4 beta'

def main():
    if not os.path.exists(config.WORKSPACE_FOLDER):
        os.makedirs(config.WORKSPACE_FOLDER)
    os.chdir(config.WORKSPACE_FOLDER)
    _Initialize()
    while(True):
        print('==========')
        print('欢迎使用%s\nVersion: %s' % (PRODUCTION_NAME, PRODUCTION_VERSION))
        print('0.自动收集新图片')
        print('1.检查数据库及磁盘中无效图片')
        print('2.备份数据库')
        print('3.修复数据库')
        print('4.删除指定歌手(包括相关图片)')
        print('5.仅删除指定图片')
        print('6.退出')
        strTmp = raw_input('请输入要使用的功能：')
        choice = re.findall(r'\d+', strTmp)[0]
        if(choice == '0'):
            if AutoCollectPic():
                print('图片备份完成')
            else:
                print('图片备份失败')
        elif(choice == '1'):
            ChkInvPic()
        elif(choice == '2'):
            BackupDB()
        elif(choice == '3'):
            RepairDB()
        elif(choice == '4'):
            DeleteArtist()
        elif(choice == '5'):
            DelPic()
        else:
            exit()
        print('\r\n')
        print('\r\n')
    return True

def _Initialize():
    global m_dDatabase
    m_dDatabase = database.CDatabase(config.DATABASE_NAME) 

def DeleteArtist():
    res = m_dDatabase.GetArtistName(-1)
    lstArtistsName = []
    for row in res:
        lstArtistsName.append(row[0])
    lstResult = delartpic.DeleteArtist(lstArtistsName)
    if lstResult == -1:
        return True
    strMsg = "你确定要删除以下歌手及相关图片： "
    print lstResult
    for i in lstResult:
        strMsg += lstArtistsName[i] + ", "
    if raw_input(strMsg + "(y/n)") == "y":
        for i in lstResult:
            m_dDatabase.DeleteArtistByName(lstArtistsName[i])
        m_dDatabase.UpdateData()
        print("成功删除指定歌手及图片")

def BackupDB():
    nIndex = fileio.GetValidFileIndex(config.DATABASE_NAME + "._%d.bak")
    if(backupdb.BackupDb(config.DATABASE_NAME, config.DATABASE_NAME + "._%d.bak" % nIndex)):
        print('数据库备份成功')
        return True
    else:
        print('数据库备份失败')
        return False

def RepairDB():
# 此函数主要找到一个可用的文件名做临时文件名
# 再调用备份函数备份数据库，最后重命名
    if not BackupDB():
        return False
    tmpFn = config.DATABASE_NAME + ".tmp"
    if not backupdb.BackupDb(config.DATABASE_NAME, tmpFn):
        print('修复数据库出错')
        return False
    # 使用新数据库
    os.remove(config.DATABASE_NAME)
    os.rename(tmpFn, config.DATABASE_NAME)
    print("修复数据库成功!")
    return True


def AutoCollectPic():
    print(m_dDatabase)
    lstFiles = os.listdir(config.PICTURES_FOLDER)
    bf = backup.CBackup(config.PICTURES_FOLDER, config.BACKUPS_FOLDER)
    for FileName in lstFiles:
        if not os.path.isfile(config.PICTURES_FOLDER + FileName):
            continue
        fileid = fileio.GetFileId(config.PICTURES_FOLDER + FileName )
        bf.BackupFile(FileName, m_dDatabase.NewPicture(FileName, fileid))
    m_dDatabase.UpdateData()
    return True

#####  #####
if __name__ == '__main__':
    main()
